package com.ruoyi.web.controller.system;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.Filebyte;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PartyEducation;
import com.ruoyi.system.service.IPartyEducationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 党员教育Controller
 *
 * @author ruoyi
 * @date 2021-06-23
 */
@RestController
@RequestMapping("/system/PartyEducation")
public class PartyEducationController extends BaseController {
    @Autowired
    private IPartyEducationService partyEducationService;

    /**
     * 查询党员教育列表
     */
//    @PreAuthorize("@ss.hasPermi('system:education:list')")
    @GetMapping("/list")
    public TableDataInfo list(PartyEducation partyEducation) {
        startPage();
        List<PartyEducation> list = partyEducationService.selectPartyEducationList(partyEducation);
        return getDataTable(list);
    }

    /**
     * 导出党员教育列表
     */
//    @PreAuthorize("@ss.hasPermi('system:education:export')")
    @Log(title = "党员教育", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PartyEducation partyEducation) {
        List<PartyEducation> list = partyEducationService.selectPartyEducationList(partyEducation);
        ExcelUtil<PartyEducation> util = new ExcelUtil<PartyEducation>(PartyEducation.class);
        return util.exportExcel(list, "education");
    }

    /**
     * 获取党员教育详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:education:query')")
    @GetMapping(value = "/peId/{peId}")
    public AjaxResult getInfoA(@PathVariable("peId") Long peId) {
        return AjaxResult.success(partyEducationService.selectPartyEducationById(peId));
    }

    @GetMapping(value = "/{peId}")
    public void getInfo(@PathVariable("peId") Long peId, HttpServletResponse response) {
        PartyEducation partyEducation = partyEducationService.selectPartyEducationById(peId);
        String path = partyEducation.getPeUrl().replace("profile", RuoYiConfig.getProfile());
        OutputStream os = null;
        InputStream is = null;
        OutputStream out = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("video" + "/" + path.substring(path.indexOf(".") + 1));
            response.setHeader("Content-Disposition", "attachment;filename=" + new String("".getBytes("utf-8"), "iso-8859-1"));
            //读取流
            File f = new File(path);
            byte[] byte1 = Filebyte.Filebyte(f);
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            System.out.println(byte1.length);
            bos.write(byte1);
            bos.flush();
        } catch (IOException e) {
            AjaxResult.error("下载附件失败,error:" + e.getMessage());
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {

            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {

            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {

            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {

            }
            try {
                if (os != null) {
                    os.close();
                }

            } catch (IOException e) {

            }
        }
//        return AjaxResult.success(partyEducation);
    }

    /**
     * 新增党员教育
     */
//    @PreAuthorize("@ss.hasPermi('system:education:add')")
    @Log(title = "党员教育", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(PartyEducation partyEducation, MultipartFile file) {
        if (null != file) {
            try {
                String profile = RuoYiConfig.getProfile();
                byte[] bytes = file.getBytes();
                //文件夹
                Path path2 = Paths.get(profile + "/" + partyEducation.getPeTitle());
                //具体文件
                Path path = Paths.get(profile + "/" + partyEducation.getPeTitle() + "/" + file.getOriginalFilename());
                File file1 = path.toFile();
                //创建文件夹
                if (!file1.exists()) {
                    path2.toFile().mkdirs();
                }
                if (file1.isFile()) {
                    return AjaxResult.error("文件上传失败,文件存在");
                } else {
                    Files.write(path, bytes);//创建文件
                    partyEducation.setPeUrl("profile/" + partyEducation.getPeTitle() + "/" + file.getOriginalFilename());
                }
            } catch (Exception e) {

            }
        }

        return toAjax(partyEducationService.insertPartyEducation(partyEducation));
    }

    /**
     * 修改党员教育
     */
//    @PreAuthorize("@ss.hasPermi('system:education:edit')")
    @Log(title = "党员教育", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(PartyEducation partyEducation, MultipartFile file) {
        if (null != file) {
            try {
                String profile = RuoYiConfig.getProfile();
                byte[] bytes = file.getBytes();
                //文件夹
                Path path2 = Paths.get(profile + "/" + partyEducation.getPeTitle());
                //具体文件
                Path path = Paths.get(profile + "/" + partyEducation.getPeTitle() + "/" + file.getOriginalFilename());
                File file1 = path.toFile();
                //创建文件夹
                if (!file1.exists()) {
                    path2.toFile().mkdirs();
                }
                if (file1.isFile()) {
                    file1.delete();
                } else {
                    Files.write(path, bytes);//创建文件
                    partyEducation.setPeUrl("profile/" + partyEducation.getPeTitle() + "/" + file.getOriginalFilename());
                }
            } catch (Exception e) {

            }
        }
        return toAjax(partyEducationService.updatePartyEducation(partyEducation));
    }

    /**
     * 删除党员教育
     */
//    @PreAuthorize("@ss.hasPermi('system:education:remove')")
    @Log(title = "党员教育", businessType = BusinessType.DELETE)
    @DeleteMapping("/{peIds}")
    public AjaxResult remove(@PathVariable Long[] peIds) {
        for (int i = 0; i < peIds.length; i++) {
            PartyEducation partyEducation = partyEducationService.selectPartyEducationById(peIds[i]);
            String path = partyEducation.getPeUrl().replace("profile", RuoYiConfig.getProfile());
            File file1 = new File(path);
            file1.delete();
        }
        return toAjax(partyEducationService.deletePartyEducationByIds(peIds));
    }
}
